package com.ruoyi.system.service.impl;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDictSon;
import com.ruoyi.system.mapper.SysDictSonMapper;
import com.ruoyi.system.service.ISysDictSonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysDictSonServiceImpl implements ISysDictSonService {

    @Autowired
    SysDictSonMapper sysDictSonMapper;

    @Override
    public String importSonData(List<SysDictSon> list, String dictCode) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new BusinessException("导入字典不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysDictSon sysDictSon : list) {
            try {
                sysDictSon.setDictCode(dictCode);
                Map<Object, Object> map = new HashMap<>();
                map.put("lable", sysDictSon.getLable());
                map.put("sort", sysDictSon.getSort());
                map.put("status", sysDictSon.getStatus());
                map.put("dictCode", sysDictSon.getDictCode());
                this.add(map);
                successNum++;
                successMsg.append("<br/>" + successNum + "、采购日期 " + sysDictSon.getLable() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、采购日期 " + sysDictSon.getLable() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<Map<String, Object>> findDictSonListByDictCode(String dictCode) {
        return sysDictSonMapper.findDictSonListByDictCode(dictCode);
    }

    @Override
    public int add(Map map) {
        return sysDictSonMapper.add(map);
    }

    @Override
    public Map<String, Object> findDictSonById(String id) {
        return sysDictSonMapper.findDictSonById(id);
    }

    @Override
    public int edit(Map map) {
        return sysDictSonMapper.edit(map);
    }

    @Override
    public int deleteSonByIds(String ids) {
        String[] array = ids.split(",");
        int num = 0;
        for (int i = 0; i < array.length; i++) {
            num += sysDictSonMapper.removeById(array[i]);
        }
        return num;
    }
}
